<?php
class JDOAuthV2 {

	private $authorize_url = 'https://oauth.jd.com/oauth/authorize';
	private $token_url = 'https://oauth.jd.com/oauth/token';
	private $appkey = '';
	private $appsecret = '';
	
	function __construct($appkey, $appsecret)
	{
		$this->appkey = $appkey;
		$this->appsecret = $appsecret;
	}

	public function getAuthorizeURL($callbackurl, $state='MODOER', $scope='read')
	{
		$view = _G('in_mobile') ? '&view=wap' : '';
		$url = $this->authorize_url . '?'
			. 'response_type=code'
			. '&client_id=' . $this->appkey
			. '&redirect_uri=' . urlencode($callbackurl)
			. '&state=' . $state
			. '&scope=' . $scope
			. $view;
		return $url;
	}


	/**
	 * uid：授权用户对应的京东ID
	 * user_nick：授权用户对应的京东昵称
	 * expires_in：失效时间（从当前时间算起，单位：秒）
	 * time：授权的时间点（UNIX时间戳，单位：毫秒）
	 * token_type：token类型（暂无意义）
	 * @param  [type] $code        [description]
	 * @param  [type] $callbackurl [description]
	 * @return [type]              [description]
	*/
	public function getAccessToken($code, $callbackurl)
	{
		$token = array();
		$token_url = $this->token_url . '?' 
			. 'grant_type=authorization_code'
			. '&code='.$code
			. '&client_id='.$this->appkey
			. '&client_secret='.$this->appsecret
			. '&state=MODOER'
			. '&redirect_uri='.urlencode($callbackurl);

		$response = http_get($token_url);
		if($response) {
			$token = json_decode($response);
			if($token) {
				if(!$token->code != '') {
	                echo "<h3>error:</h3>" . $token->error;
	                exit;
				}
			}
		}
		return $token;
	}

}

class JDClientV2 {

	private $sdk = null;

	private $appkey = '';
	private $appsecret = '';
	private $token = '';
	private $openid = '';
	
	function __construct($appkey, $appsecret, $token, $openid='') {
		$this->appkey = $appkey;
		$this->appsecret = $appsecret;
		$this->token = $token;
		if($openid == '') {
			$o = QQOAuthV2($appkey, $appsecret);
			$this->openid = $o->getOpenid($token);
		} else {
			$this->openid = $openid;
		}
	}

	function get_user_info() {
	    $get_user_info = "https://graph.qq.com/user/get_user_info?"
	        . "access_token=" . $this->token
	        . "&oauth_consumer_key=" . $this->appkey
	        . "&openid=" . $this->openid
	        . "&format=json";
	    $info = http_get($get_user_info);
	    $arr = json_decode($info, true);
	    return $arr;
	}

}

/** end **/